﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace Files
{
    /// <summary>
    /// 文件类(主要是网页内容)
    /// </summary>
    public class FileClass
    {
        #region 全局变量

        /// <summary>
        /// 网址
        /// </summary>
        public static string Url = "";
        /// <summary>
        /// 错误内容(当获取网页内容错误时返回的错误信息)
        /// </summary>
        public static string ErrorContent = "Error!Error!Error!";
        /// <summary>
        /// 下载地址
        /// </summary>
        private string _DownLoadUrl = "";
        /// <summary>
        /// 保存文件路径(路径全名，包括文件名)
        /// </summary>
        private string _SaveFilePath = "";
        /// <summary>
        /// 字符编码
        /// </summary>
        private static Encoding _Encoding;

        #endregion

        #region 变量设置和获取

        /// <summary>
        /// 设置和获取字符编码
        /// </summary>
        public static Encoding Encoding
        {
            #region 逻辑
            set 
            {
                try
                {
                    if (value != null)
                    {
                        _Encoding = value;
                    }
                    else
                    {
                        _Encoding = Encoding.GetEncoding("GB2312");
                    }
                }
                catch
                {
                    _Encoding = Encoding.GetEncoding("GB2312");
                }
            }
            get 
            {
                if (_Encoding == null)
                {
                    _Encoding = Encoding.GetEncoding("GB2312"); 
                }
                return _Encoding;
            }
            #endregion
        }

        /// <summary>
        /// 下载地址
        /// </summary>
        public string DownLoadUrl
        {
            set { _DownLoadUrl = value; }
            get { return _DownLoadUrl; }
        }

        /// <summary>
        /// 保存文件路径(路径全名，包括文件名)
        /// </summary>
        public string SaveFilePath
        {
            set { _SaveFilePath = value; }
            get { return _SaveFilePath; }
        }

        #endregion

        #region 获取网页右键内容

        /// <summary>
        /// 获得网页右键内容(可以配置页面的字符编码，如果不设置字符编码，默认为GB2312)(网页包括html，xml，shtml等)
        /// </summary>
        /// <returns>string</returns>
        public static string GetPageContent()
        {
            string content = "";
            #region 逻辑
            HttpWebResponse response = null;
            Stream streams = null;
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);                        //(1)声明一个HttpWebRequest请求
                request.Timeout = 30000;                                                                //(2)设置连接超时时间
                request.Headers.Set("Pragma", "no-cache");                                              //(3)设置页面无缓存
                response = (HttpWebResponse)request.GetResponse();                                      //(4)得到回应
                streams = response.GetResponseStream();                                                 //(5)将回应转换为数据流
                Encoding encodings = Encoding;                                                          //(6)对数据量进行编码解析，以便正常读取
                reader = new StreamReader(streams, encodings);                                          //(7)创建读取流
                content = reader.ReadToEnd();                                                           //(8)读取流信息
            }
            catch
            {
                content = ErrorContent;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();                                                                     //(9)关闭读取流
                }
                if (streams != null)
                {
                    streams.Close();                                                                    //(10)关闭数据流
                }
                if (response != null)
                {
                    response.Close();                                                                   //(11)关闭网络相应流
                }
            }
            #endregion
            return content;
        }

        /// <summary>
        /// 获得网页右键内容(可以配置页面的字符编码，如果不设置或者设置出错字符编码，默认为GB2312)(网页包括html，xml，shtml等)
        /// </summary>
        /// <param name="url"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string GetPageContent(string url, string charset)
        {
            string content = "";
            #region 逻辑
            HttpWebRequest request = null;
            WebResponse response = null;
            Stream streams = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1)";
                response = request.GetResponse();
                streams = response.GetResponseStream();
                Encoding encodings = null;
                try
                {
                    encodings = Encoding.GetEncoding(charset);
                }
                catch
                { 
                    encodings = Encoding.GetEncoding("gb2312");
                }
                reader = new StreamReader(streams, encodings);
                content = reader.ReadToEnd();
            }
            catch
            {
                content = ErrorContent;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (streams != null)
                {
                    streams.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            #endregion
            return content;
        }

        /// <summary>
        /// 获得网页右键内容(针对网页编码格式是UTF-8的页面适用)(网页包括html，xml，shtml等)
        /// </summary>
        /// <returns>string</returns>
        public static string GetWebPageContent()
        {
            string content = "";
            #region 逻辑
            HttpWebResponse response = null;
            Stream streams = null;
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);                        //(1)声明一个HttpWebRequest请求
                request.Timeout = 30000;                                                                //(2)设置连接超时时间
                request.Headers.Set("Pragma", "no-cache");                                              //(3)设置页面无缓存
                response = (HttpWebResponse)request.GetResponse();                                      //(4)得到回应
                streams = response.GetResponseStream();                                                 //(5)将回应转换为数据流
                Encoding encodings = Encoding.GetEncoding("utf-8");                                    //(6)对数据量进行编码解析，以便正常读取
                reader = new StreamReader(streams, encodings);                                          //(7)创建读取流
                content = reader.ReadToEnd();                                                           //(8)读取流信息
            }
            catch
            {
                content = ErrorContent;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();                                                                     //(9)关闭读取流
                }
                if (streams != null)
                {
                    streams.Close();                                                                    //(10)关闭数据流
                }
                if (response != null)
                {
                    response.Close();                                                                   //(11)关闭网络相应流
                }
            }
            #endregion
            return content;
        }

        /// <summary>
        /// 获得网页右键内容(针对网页编码格式是GB2312的页面适用)(网页包括html，xml，shtml等)
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns>string</returns>
        public static string GetWebPageContent(string url)
        {
            string content = "";
            #region 逻辑
            HttpWebRequest request = null;
            WebResponse response = null;
            Stream streams = null;
            StreamReader reader = null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1)";
                response = request.GetResponse();
                streams = response.GetResponseStream();
                reader = new StreamReader(streams, Encoding.GetEncoding("gb2312"));
                content = reader.ReadToEnd();
            }
            catch
            {
                content = ErrorContent;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (streams != null)
                {
                    streams.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            #endregion
            return content;
        }

        #endregion

        #region 判断逻辑(返回值为bool或者int型)

        /// <summary>
        /// 查看网址是否存在，若存在返回true，否则返回false
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns>bool</returns>
        public static bool IsExistUrl(string url)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            #region 逻辑
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusDescription.ToString().ToUpper() == "OK")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request = null;
                }
            }
            #endregion
        }

        #endregion

        #region 文件上传和下载

        /// <summary>
        /// 下载文件(0:下载失败;1:文件已经存在;2:下载成功)(该方法必须先对下载地址DownLoadUrl和保存文件路径SaveFilePath进行赋值)
        /// </summary>
        /// <returns>int</returns>
        public int DownLoadFile()
        {
            int index = 0;
            #region 逻辑
            try
            {
                if (!File.Exists(SaveFilePath))
                {
                    WebClient wc = new WebClient();
                    wc.DownloadFile(DownLoadUrl, SaveFilePath);
                    index = 2;
                }
                else
                {
                    index = 1;
                }
            }
            catch
            {
                index = 0;
            }
            #endregion
            return index;
        }

        /// <summary>
        /// 下载文件(0:下载失败;1:文件已经存在;2:下载成功)
        /// </summary>
        /// <param name="source_url">下载地址</param>
        /// <param name="target_url">保存地址</param>
        /// <returns>int</returns>
        public int DownLoadFile(string source_url, string target_url)
        {
            int index = 0;
            #region 逻辑
            try
            {
                if (!File.Exists(target_url))
                {
                    WebClient wc = new WebClient();
                    wc.DownloadFile(source_url, target_url);
                    index = 2;
                }
                else
                {
                    index = 1;
                }
            }
            catch
            {
                index = 0;
            }
            #endregion
            return index;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source_url"></param>
        /// <param name="target_url"></param>
        /// <returns></returns>
        public int UpLoadFile(string source_url, string target_url)
        {
            int index = 0;
            #region 逻辑
            try
            {
                if (!File.Exists(target_url))
                {
                    WebClient wc = new WebClient();
                    wc.UploadFile(target_url, source_url);
                    index = 2;
                }
                else
                {
                    index = 1;
                }
            }
            catch
            {
                index = 0;
            }
            #endregion
            return index;
        }

        #endregion
    }
}
